package com.example.campuslink.commen.dialog

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.example.campuslink.R
import com.example.campuslink.commen.core.CoreDialog
import com.example.campuslink.commen.enums.SecondHandEnum
import com.example.campuslink.databinding.DialogSecondHandBinding
import com.example.campuslink.ui.activity.PublicActivity
import java.lang.ref.WeakReference

class SecondHandDialog : CoreDialog<DialogSecondHandBinding>(R.layout.dialog_second_hand) {
    private lateinit var adapter: ArrayAdapter<String>
    private val secondHandList: List<String> = SecondHandEnum.getAllLabels()
    private var secondHand = SecondHandEnum.RECOMMENDED.label
    private var activityRef: WeakReference<PublicActivity>? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        adapter =
            ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, secondHandList)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item)
        val activity = parentFragment?.activity ?: activity
        if (activity is PublicActivity) {
            activityRef = WeakReference(activity)
        }
    }

    override fun setupViews() {
        binding.spinnerShowSecondHand.adapter = adapter
        binding.spinnerShowSecondHand.setOnItemSelectedListener(object :
            AdapterView.OnItemSelectedListener {
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                secondHand = "# ${secondHandList[p2]}"
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {

            }
        })
        binding.btnCancel.setOnClickListener {
            dismiss()
        }
        binding.btnConfirm.setOnClickListener({
            activityRef?.get()?.addTopic(secondHand)
            dismiss()
        })
    }

    override fun createBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): DialogSecondHandBinding {
        return DialogSecondHandBinding.inflate(inflater, container, false)
    }
}